//
//  RWFileDispatch.m
//  RWTool
//
//  Created by Ray on 2021/11/17.
//

#import "RWFileDispatch.h"

@implementation RWFileDispatch

#pragma mark - dataFile Operation

/// 数据信息解挡获取
/// @param pKey 数据key
/// @param filePath 文件路径
+ (id)loadDataWithKey:(NSString *)pKey fromFile:(NSString *)filePath {
    
    id obj = nil;
    
    if ( [[NSFileManager defaultManager] fileExistsAtPath:filePath] ) {
        
        NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];
        
        if (!data) {
            return nil;
        }
        @try {
            NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
            
            BOOL y = [unarchiver containsValueForKey:pKey];
            
            if (y) {
                obj = [unarchiver decodeObjectForKey:pKey];
                [unarchiver finishDecoding];
            }
        }
        @catch (NSException *exception) {
            obj = nil;
        }
        @finally {
            
        }
        
    } else {
        obj = nil;
    }
    
    return obj;
}

/// 数据信息归档保存
/// @param data 数据对象
/// @param pKey 数据key
/// @param filePath 文件路径
+ (void)saveData:(id)data whithkey:(NSString *)pKey toFile:(NSString *)filePath {
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }
    
    NSMutableData *writeData = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:writeData];
    
    [archiver encodeObject:data forKey:pKey];
    [archiver finishEncoding];
    
    if ([writeData writeToFile:filePath atomically:YES]) {
        
        NSLog(@"数据写入成功");
    } else {
        
        NSLog(@"数据写入失败");
    }
}

/// 删除数据信息归档文件
/// @param filePath 文件路径
+ (void)deleteDataFile:(NSString *)filePath error:(NSError *)error {
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        return;
    }
    
    if([[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
        
        NSLog(@"文件移除成功");
        
    } else {
        NSLog(@"error=%@", error);
        NSAssert(error, @"用户信息删除出错，此警告只会在测试的过程中出现");
    }
}

#pragma mark - dataFile Path

/// 数据信息文件路径
+ (NSString *)dataFile:(NSString *)fileName dir:(NSString *)dir {
    
    NSMutableString* file = [NSMutableString string];
    [file appendFormat:@"%@%@", [self dataDirectory:dir], fileName];

    return file;
}

/// 数据信息文件存储目录
+ (NSString *)dataDirectory:(NSString *)dir {
    
    NSString* appSupportDir = [self getDocumentDirectory];
    NSMutableString* persistentDataDir = [NSMutableString string];
    
    if (appSupportDir) {
        
        NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
        
        [persistentDataDir appendString:appSupportDir];
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            [persistentDataDir appendFormat:@"%@/%@/",appBundleID, dir];
        }else {
            [persistentDataDir appendFormat:@"%@/%@/",appBundleID, dir];
        }
    }
    
    //判断文件夹是否存在
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:persistentDataDir isDirectory:nil];
    
    //如果不存在则创建文件夹
    if (!fileExists) {
        //创建文件夹
        NSError *error = nil;
        [[NSFileManager defaultManager] createDirectoryAtPath:persistentDataDir withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            
            NSLog(@"文件夹创建失败error=%@",error.description);
        }
    }
    
    return persistentDataDir;
}

+ (NSString *)getDocumentDirectory {
    
    NSArray* documentsDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if (documentsDirectories.count > 0) {
        
        NSString *documentsDirectory = [documentsDirectories objectAtIndex:0];
        documentsDirectory = [NSString stringWithFormat:@"%@/",documentsDirectory];
        return documentsDirectory;
    }
    return nil;
}

@end
